package com.gree.shyun.util;

import com.gree.shyun.bean.AddIcon;
import com.gree.shyun.server.db.util.TextUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageUtil {
    /**
     * 检测图片长宽是否大于200像素
     * @param f
     * @return
     * @throws IOException
     */
    public static boolean check(File f) throws IOException {
        BufferedImage bufImg = ImageIO.read(f); //读取图
        if(bufImg.getWidth()>=128&&bufImg.getHeight()>=128){
            return true;
        }
        return false;
    }

    /**
     *  裁剪
     * @param srcFile
     * @param dest
     * @param addIcon
     * @return
     */
    public static boolean zoomImages(File srcFile,String dest, AddIcon addIcon) throws IOException {
        String fileName;
        if(TextUtils.isEmpty(addIcon.getFilename())){
            fileName = FileUtil.getFilename(srcFile.getPath());
        }else{
            fileName = addIcon.getFilename()+".png";
        }
        String mdpi = dest+"/res/mipmap-mdpi/"+fileName;
        String hdpi = dest+"/res/mipmap-hdpi/"+fileName;
        String xhdpi = dest+"/res/mipmap-xhdpi/"+fileName;
        String xxhdpi = dest+"/res/mipmap-xxhdpi/"+fileName;
        String xxxhdpi = dest+"/res/mipmap-xxxhdpi/"+fileName;
//        BufferedImage bufImg = ImageIO.read(srcFile); //读取图
//        if(bufImg.getWidth()>bufImg.getHeight()){
//
//        }else{
//
//        }
        try {
            boolean isCover = addIcon.isCover();
            zoomImage(srcFile,mdpi,32,32,isCover);
            zoomImage(srcFile,hdpi,48,48,isCover);
            zoomImage(srcFile,xhdpi,64,64,isCover);
            zoomImage(srcFile,xxhdpi,96,96,isCover);
            zoomImage(srcFile,xxxhdpi,128,128,isCover);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
    /**
     *  图片缩放
     * @param srcFile
     * @param dest
     * @param w
     * @param h
     * @throws Exception
     */
    public static void zoomImage(File srcFile,String dest,int w,int h,boolean isCover) throws Exception {
        double wr=0,hr=0;
        File destFile = new File(dest);
        if(!isCover&&destFile.exists()){
            return;
        }
        BufferedImage bufImg = ImageIO.read(srcFile); //读取图片
        Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);//设置缩放目标图片模板
        wr=w*1.0/bufImg.getWidth();     //获取缩放比例
        hr=h*1.0 / bufImg.getHeight();

        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
        Itemp = ato.filter(bufImg, null);
        try {
            ImageIO.write((BufferedImage) Itemp,dest.substring(dest.lastIndexOf(".")+1), destFile); //写入缩减后的图片
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
